package com.yh.csx.bsf.ods;

import com.yh.csx.bsf.core.util.PropertyUtils;
import com.yh.csx.bsf.core.util.StringUtils;
import lombok.var;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.*;

public class CommonUtils {
    public static List<String> getSubscribeDbs(){
        var dbs="";
       for(var ip :getIps()){
           dbs = PropertyUtils.getPropertyCache("increment.subscribe."+ip,"");
           if(!StringUtils.isEmpty(dbs)){
                break;
           }
       }
        if(!StringUtils.isEmpty(dbs)){
            var as = dbs.split(",");
            return Arrays.asList(as);
        }
        return new ArrayList<String>();
    }

    public static List<String> getIps(){
        var list = new ArrayList<String>();
        try {
            Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
            InetAddress ip = null;
            while (allNetInterfaces.hasMoreElements()) {
                NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
                if (netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()|| netInterface.isPointToPoint()) {
                    continue;
                } else {
                    Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
                    while (addresses.hasMoreElements()) {
                        ip = addresses.nextElement();
                        if (ip != null && ip instanceof Inet4Address) {
                            list.add( ip.getHostAddress());
                        }
                    }
                }
            }
        } catch (Exception e) {
        }
        return list;
    }
}
